#include "mystdio.h"
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>

#define MODE 0666

//判断刷新
#define TRY_FLUSH  1
#define MUST_FLUSH 2

//定义函数
myFile* myfopen(const char* pathname, const char* mode)
{
  int flags = 0;//记录文件的打开方式i
  int fd = -1;
  if(strcmp(mode,"w") == 0)
  {
    fd = open(pathname, O_WRONLY | O_CREAT | O_TRUNC, MODE);
    //构造file对象返回
    flags = O_WRONLY | O_CREAT | O_TRUNC; 
  }
  else if(strcmp(mode,"a") == 0)
  {
    fd = open(pathname, O_WRONLY | O_CREAT | O_APPEND, MODE);
    //构造file对象返回
    flags = O_WRONLY | O_CREAT | O_APPEND;
  }
  else if(strcmp(mode, "r") == 0)
  {
    fd = open(pathname, O_RDONLY);
    //构造file对象返回
    flags = O_RDONLY;
  }
  else{
    //w+,a+,r+
    //...
  }
  //构造myFile对象
  if(fd == -1)
    return NULL;
  myFile* file = (myFile*)malloc(sizeof(myFile));
  file->fd = fd;
  file->flags = flags;
  file->flush_mode = LINE_BUFF;
  file->pos = 0;
  file->ca = SIZE;

  return file;
}

int myfputs(const char* str, myFile* file)
{
  //是将用户缓冲区的内容写到语言级缓冲区中--拷贝函数
  //注意语言级缓冲区中如c语言中包含\n
  memcpy(file->buff + file->pos,str,strlen(str));
  file->pos += strlen(str);
  //尝试将语言级缓冲区刷新
  
  myfflush(file);
  return 0;
}


void myfflushcore(myFile* fp,int flag)
{
  if(fp->flush_mode & LINE_BUFF || flag == MUST_FLUSH)
  {
    if(fp->buff[fp->pos - 1] == '\n' || flag == MUST_FLUSH)
    {
      write(fp->fd,fp->buff,sizeof(fp->buff));
      fp->pos = 0;
    }
  }
  else if(fp->flush_mode & NONE_BUFF)
  {
    // 
  }
  else if(fp->flush_mode & FULL_BUFF)
  {
    //
  }
}

void myfclose(myFile* fp)
{
  //强制刷新
  myfflushcore(fp, MUST_FLUSH);
  //关闭文件
  close(fp->fd);
  //释放资源
  free(fp);
}


void myfflush(myFile* fp)
{
  myfflushcore(fp,TRY_FLUSH);
}
